'use client';

import type { IPath, IQueryQqAuthUrlBody } from '@/interfaces';
import type { TBody, TMetadata } from '@/types';
import { type FormEvent, useState } from 'react';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { queryQqAuthUrl } from '@/services/api';
import { useTranslations } from 'use-intl';

export default function QqLogin({
  data,
  metadata,
}: {
  data: IPath;
  metadata: TMetadata;
}) {
  const t = useTranslations('LoginPage');
  const [disableLogin, setDisableLogin] = useState(false);
  const { show } = useToast();

  const queryQqAuthUrlMutation = useMutation(
    async (variables: TBody<IQueryQqAuthUrlBody>) => {
      return (await queryQqAuthUrl(variables)) as string;
    },
  );

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    e.stopPropagation();

    try {
      const qqConfig = data.qqConfig;
      if (!qqConfig || !qqConfig.enable) {
        show({
          type: 'DANGER',
          message: t('qqLoginDisabled'),
        });
        return;
      }

      const url = await queryQqAuthUrlMutation.mutateAsync({
        data: { alias: '' },
      });
      setDisableLogin(true);

      show({
        message: t('qqAuthorizationPrompt'),
        type: 'PRIMARY',
      });

      setTimeout(() => {
        show({
          message: t('redirecting'),
          type: 'PRIMARY',
        });
      }, 1000);

      setTimeout(() => {
        location.href = url;
      }, 1500);
    } catch (e) {
      queryQqAuthUrlMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <form onSubmit={onSubmit}>
      {data.qqConfig && data.qqConfig.enable ? (
        <div className="my-3">
          <button
            disabled={queryQqAuthUrlMutation.isLoading || disableLogin}
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {queryQqAuthUrlMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            {disableLogin ? (
              <span>{t('redirecting')}</span>
            ) : (
              <span>{t('loginPrompt')}</span>
            )}
          </button>
        </div>
      ) : (
        <div className="my-3">
          <button
            disabled
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {t('qqLoginDisabled')}
          </button>
        </div>
      )}
    </form>
  );
}
